const mysql = require('mysql2/promise');
const redis = require('redis');
require('dotenv').config();

// MySQL连接池配置
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// Redis客户端配置
const redisClient = redis.createClient({
  url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`
});

// 准备就绪
redisClient.on('ready', () => {
  console.log('Redis 准备就绪');
});

// 初始化Redis连接
const initRedis = async () => {
  await redisClient.connect();
};

// Redis错误处理
redisClient.on('error', (err) => {
  console.error('Redis错误:', err);
});

// Redis重连机制
redisClient.on('reconnecting', () => {
  console.log('Redis正在重连...');
});

module.exports = {
  pool,
  redisClient,
  initRedis
};